import base64
from datetime import datetime


def _create_ssdp(field_names):
    # 非移动网关参数
    attrs = ["Api_ID", "Api_Version", "App_Sub_ID", "App_Token", "ENV", "Partner_ID", "Sign", "Sys_ID", "Time_Stamp",
             "User_Token"]
    # 移动网关参数不需要sys_id
    attrs_app = ["Api_ID", "Api_Version", "App_ID", "App_Sub_ID", "App_Token", "App_Version", "Divice_ID",
                 "Divice_Version", "ENV", "OS_Version", "Partner_ID", "Sign", "Time_Stamp", "User_Token"]

    ssdp_str = ""

    if field_names.get('App_Version', '') != '':
        for i in range(14):
            if i == 8 and ('ENV' not in field_names or field_names.get('ENV', '') == ''):
                continue
            else:
                ssdp_str += f"{attrs_app[i]}={field_names.get(attrs_app[i], '')}&"
    else:
        for i in range(10):
            if i == 4 and ('ENV' not in field_names or field_names.get('ENV', '') == ''):
                continue
            else:
                ssdp_str += f"{attrs[i]}={field_names.get(attrs[i], '')}&"

    # 移除最后一个'&'字符
    if ssdp_str:
        ssdp_str = ssdp_str[:-1]

    return ssdp_str


def create_ssdp():
    field_names = {
        "Api_ID": "snowbeer.MES.test.SaveDataIOT",
        "Api_Version": "1.0",
        "App_Sub_ID": "1200003H0002",
        "App_Token": "6318815045964181b3f30084e8d1ba4f",
        "App_ID": "",  # 移动应用编码，为空字符串则表示不生成移动网关的ssdp
        "App_Version": "",  # 移动应用版本
        "Divice_ID": "",  # 移动设备号
        "Divice_Version": "",  # 设备版本
        "OS_Version": "",  # 设备操作系统版本
        # "ENV": "",  # 该参数根据实际需求选择是否需要添加
        "Partner_ID": "12000000",
        "Sign": "NO_SIGN",  # 如果服务不需要签名，则数值为 NO_SIGN
        "Sys_ID": "1200003H",
        "Time_Stamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f')[:-3],
        "User_Token": ""  # 一般服务的User_Token为空字符串
    }
    ssdp_str = _create_ssdp(field_names)
    return base64.b64encode(ssdp_str.encode('utf-8')).decode('utf-8')


def test():
    field_names = {
        "Api_ID": "snowbeer.MES.test.SaveDataIOT",
        "Api_Version": "1.0",
        "App_Sub_ID": "1200003H0002",
        "App_Token": "6318815045964181b3f30084e8d1ba4f",
        "App_ID": "",  # 移动应用编码，为空字符串则表示不生成移动网关的ssdp
        "App_Version": "",  # 移动应用版本
        "Divice_ID": "",  # 移动设备号
        "Divice_Version": "",  # 设备版本
        "OS_Version": "",  # 设备操作系统版本
        # "ENV": "",  # 该参数根据实际需求选择是否需要添加
        "Partner_ID": "12000000",
        "Sign": "NO_SIGN",  # 如果服务不需要签名，则数值为 NO_SIGN
        "Sys_ID": "1200003H",
        "Time_Stamp": "2024-11-21 20:46:14:638",
        "User_Token": ""  # 一般服务的User_Token为空字符串
    }
    ssdp_str = _create_ssdp(field_names)
    print(f"原始ssdpStr: \n{ssdp_str}")
    base64_string = base64.b64encode(ssdp_str.encode('utf-8')).decode('utf-8')
    print(f"BASE64编码后结果:\n{base64_string}")


if __name__ == "__main__":
    test()


